package org.dromara.quickswing.excutor;

import javax.swing.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

public class QSTaskExecutor {
    private final ExecutorService executorService;
    public QSTaskExecutor(ExecutorService executorService) {
        if (executorService == null) {
            throw new IllegalArgumentException();
        } else {
            this.executorService = executorService;
        }
    }


    public <T,R> Future<R> submit(Callable<T> callable, BiFunction<T, Exception,R> function) {
        if (callable != null && function != null) {
          return this.executorService.submit(() -> {
                try {
                    T result = callable.call();
                    return function.apply(result, null);
                } catch (Exception exception) {
                    return function.apply(null, exception);
                }
            });
        } else {
            throw new IllegalArgumentException();
        }
    }

    public <T> void execute(Callable<T> callable, BiConsumer<T, Exception> consumer) {
        if (callable != null && consumer != null) {
            this.executorService.submit(() -> {
                try {
                    T result = callable.call();
                    SwingUtilities.invokeLater(() -> consumer.accept(result, null));
                } catch (Exception exception) {
                    SwingUtilities.invokeLater(() -> consumer.accept(null, exception));
                }

            });
        } else {
            throw new IllegalArgumentException();
        }
    }


}
